package com.guli.mall.wms.mq;
/*
 * @Author 罗俊
 * @date 2020/11/28 - 12:51 下午
 *
 */

import com.guli.common.constant.WareConstant;
import com.guli.mall.wms.entity.WareOrderTaskDetailEntity;
import com.guli.mall.wms.entity.WareOrderTaskEntity;
import com.guli.mall.wms.service.WareOrderTaskDetailService;
import com.guli.mall.wms.service.WareOrderTaskService;
import com.guli.mall.wms.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * 扣减库存
 */
@Component
@RabbitListener(queues = {WareConstant.STOCK_DEDUCTION_QUEUE})
@Slf4j
public class DeductStock {

    @Resource
    WareOrderTaskService wareOrderTaskService;

    @Resource
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Resource
    WareSkuService wareSkuService;

    @Transactional
    @RabbitHandler
    public void deductStockByOrderSn(String orderSn, Channel channel, Message message) {
        try {
            log.info("订单号 orderSn = {}支付完成，现在真正的扣减库存", orderSn);

            List<Long> wareOrderTaskDetailIds = wareOrderTaskService.getWareOrderTaskDetailIdByOrderSn(orderSn);

            boolean update = wareOrderTaskDetailService.updateMultipleWareOrderTaskDetailStatusByIdAndOldStatus(wareOrderTaskDetailIds, WareConstant.LockStatus.LOCKED, WareConstant.LockStatus.DEDUCTION);

            if (update) {
                log.info("订单号 orderSn = {}的订单，已将其库存扣减记录的状态从【{}】更改为【{}】", orderSn, WareConstant.LockStatus.LOCKED.getMessage(), WareConstant.LockStatus.DEDUCTION.getMessage());

                boolean success = wareSkuService.deductStockByWareOrderTaskDetailIds(wareOrderTaskDetailIds);

                if (success) {
                    log.info("扣减订单id = {}，的库存以及解锁库存成功", orderSn);
                }
            } else {
                log.warn("没有将 orderSn = {}的订单的库存状态做更新（保证幂等性）", orderSn);
            }


            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

    }
}
